import React, { useEffect, useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { NavBar, Toast } from 'antd-mobile'
import { getCityHotAPI, getCityListAPI } from '../../apis/cityList'
import { getCurrentCity } from '../../utils'
import { AutoSizer, List } from 'react-virtualized';
import './index.scss'

const TITLE_HEIGHT = 36
const NAME_HEIGHT = 50
const HOT_CITY = ['北京', '上海', '广州', '深圳']
const formatCityIndex = (letter) => {
    switch (letter) {
        case '#':
            return '当前定位'
        case 'hot':
            return '热门城市'
        default:
            return letter.toUpperCase()
    }
}

export default function CityList() {
    const navigate = useNavigate()
    const ListRef = useRef()
    const [cityIndex, setCityIndex] = useState([])
    const [activeIndex, setActiveIndex] = useState(0)
    const [cityList, setCityList] = useState({})
    function rowRenderer({
        key, // Unique key within array of rows
        index, // Index of row within collection
        isScrolling, // The List is currently being scrolled
        isVisible, // This row is visible within the List (eg it is not an overscanned row)
        style, // Style object to be applied to row (to position it)
    }) {
        let letter = cityIndex[index]
        let list = cityList[letter]
        return (
            <div key={key} style={style} className='city'>
                <div className='title'>{formatCityIndex(letter)}</div>
                {
                    Array.from(list).map(item =>
                    (<div className='name' key={item.value} onClick={() => changeCity(item)}>
                        {item.label}
                    </div>)
                    )
                }
            </div>
        );
    }
    // 处理数据使城市按首字母排序分类
    const formatCityData = (list) => {
        let cityList = {}
        let cityIndex = []
        list.forEach(item => {
            const first = item.short.substr(0, 1)
            if (cityList[first]) {
                cityList[first].push(item)
            } else {
                cityList[first] = [item]
            }
        })

        cityIndex = Object.keys(cityList).sort()
        return {
            cityList,
            cityIndex
        }
    }
    useEffect(() => {
        async function getCityList() {
            const res = await getCityListAPI('1')
            const hotRes = await getCityHotAPI()
            const { cityList, cityIndex } = formatCityData(res.body)
            cityList['hot'] = hotRes.body
            cityIndex.unshift('hot')
            const city = await getCurrentCity()
            cityList['#'] = [city]
            cityIndex.unshift('#')
            // console.log(cityList,cityIndex)
            setCityIndex(cityIndex)
            setCityList(cityList)

        }
        getCityList()
        // setInterval(() => {
        //     ListRef.current.measureAllRows()
        // }, 1000)
    }, [])
    function changeCity({ label, value }) {
        if (HOT_CITY.indexOf(label) > -1) {
            localStorage.setItem('hkzf_city', JSON.stringify({label,value}))
            navigate(-1)
        } else {
            Toast.show({
                content: '该城市暂无房源',
                afterClose: () => {
                    console.log('after')
                },
            })
        }
    }
    const getRowHeight = ({ index }) => {
        return TITLE_HEIGHT + parseInt(cityList[cityIndex[index]].length) * NAME_HEIGHT
        // return 100
    }
    const getCityIndexList = () => {
        return cityIndex.map((item, index) => (
            <li className='city__index__item' key={item} onClick={() => toCurRow(index)}>
                <span className={activeIndex === index ? 'index-active' : ''}>
                    {item === 'hot' ? '热' : item.toUpperCase()}
                </span>
            </li>
        ))
    }
    const toCurRow = (index) => {
        setActiveIndex(index)
        ListRef.current.scrollToRow(index)
    }
    const setCurRow = ({ startIndex }) => {
        if (activeIndex !== startIndex) {
            // console.log(startIndex)
            setActiveIndex(startIndex)
        }
    }
    return (
        <div className='citylist'>
            <NavBar className='citylist__navbar' onBack={() => navigate('/home')} style={{ backgroundColor: '#f6f6f6' }}>
                城市选择
            </NavBar>
            <AutoSizer className='citylist__content'>
                {({ width, height }) =>
                    <List
                        ref={ListRef}
                        width={width}
                        height={height}
                        rowCount={cityIndex.length}
                        rowHeight={getRowHeight}
                        rowRenderer={rowRenderer}
                        onRowsRendered={setCurRow}
                        scrollToAlignment="start"
                    />}

            </AutoSizer>
            <ul className='city__index'>
                {getCityIndexList()}
            </ul>
        </div>
    )

}
